import { AfterViewInit, Component, ElementRef, Input, OnDestroy, OnInit, Renderer2, ViewChild } from '@angular/core';
import { ReplyVo } from 'src/app/model/reply-vo';
import { fromEvent } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-reply-item-embed',
  templateUrl: './reply-item-embed.component.html',
  styles: [``]
})
export class ReplyItemEmbedComponent implements OnInit, AfterViewInit, OnDestroy {
  @Input('reply')
  public item!: ReplyVo;
  @ViewChild('postsContent', { read: ElementRef })
  public postsContentEleId!: ElementRef;
  public block!: boolean;
  public modify!: boolean;
  public modifyer: number | undefined;
  public modifyDate!: Date;
  private listenFunc!: any;

  constructor(private renderer2: Renderer2) { }

  ngAfterViewInit(): void {
    //阻塞时不显示:*
    if (!this.block) {
      this.renderer2.setProperty(this.postsContentEleId.nativeElement, 'innerHTML', this.item.content);
    }
    
    this.listenFunc = fromEvent(this.postsContentEleId.nativeElement.querySelectorAll('img.lazyload'), 'load')
      .pipe(map((val: any) => val.target))
      .subscribe({
        next: res => {
          res.src = res.getAttribute('data-original');
        },
        error: err => {
        },
        complete: () => {
          console.log('[ReplyItemCLS]Completed');
        }
    });
  }

  ngOnInit(): void {
    this.block = !this.item.status
    this.modifyer = this.item.modifyMember ?? 0;
    this.modify = this.modifyer > 0;
    this.modifyDate = this.item.modifyDateTime;
  }

  ngOnDestroy(): void {
    if(this.listenFunc){
      this.listenFunc.unsubscribe();
    }
  }
}
